package developer.zyk.ability.chat.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import developer.zyk.ability.chat.bo.AssistantMessageBO;
import developer.zyk.ability.chat.bo.UserMessageBO;
import developer.zyk.ability.chat.dao.entity.ChatHistoryDO;
import developer.zyk.ability.chat.dao.entity.ChatHistoryDetailDO;
import developer.zyk.ability.chat.dao.mappers.ChatHistoryDetailMapper;
import developer.zyk.ability.chat.dao.mappers.ChatHistoryMapper;
import developer.zyk.ability.chat.param.ChatHistoryCreateParam;
import developer.zyk.ability.helper.ModelConfigHelper;
import developer.zyk.global.common.consts.ChatRole;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;

/**
 * @author zhangyongkang
 * @time 2025/4/30 16:06
 * @description
 */
@AllArgsConstructor
@Component
public class ChatHistoryService {
    private ChatHistoryMapper chatHistoryMapper;
    private ChatHistoryDetailMapper chatHistoryDetailMapper;
    private TransactionTemplate transactionTemplate;


    public List<ChatHistoryDO> findChatHistory(Long userId) {
        return chatHistoryMapper.selectList(new QueryWrapper<ChatHistoryDO>()
                .lambda()
                .eq(ChatHistoryDO::getOperateId, userId)
                .orderByDesc(ChatHistoryDO::getGmtCreate)
        );
    }

    public Long addNewChat(ChatHistoryCreateParam chatHistoryCreateParam) {
        ChatHistoryDO chatHistoryDO = new ChatHistoryDO();
        chatHistoryDO.setGmtCreate(LocalDateTime.now(ZoneId.systemDefault()));
        chatHistoryDO.setOperateId(chatHistoryCreateParam.getOperateId());
        chatHistoryDO.setOperateName(chatHistoryCreateParam.getOperateName());
        chatHistoryDO.setTitle(chatHistoryCreateParam.getMessage());
        chatHistoryDO.setModelType(
                ModelConfigHelper.modelType(chatHistoryCreateParam::getModelType)
        );

        chatHistoryMapper.insert(chatHistoryDO);
        return chatHistoryDO.getId();
    }

    public boolean deleteById(Long chatId) {
        transactionTemplate.executeWithoutResult((action) -> {
            chatHistoryMapper.deleteById(chatId);
            chatHistoryDetailMapper.delete(
                    new QueryWrapper<ChatHistoryDetailDO>()
                            .lambda()
                            .eq(ChatHistoryDetailDO::getChatId, chatId)
            );
        });
        return true;
    }


    public List<ChatHistoryDetailDO> findChatDetailByChatId(Long chatId) {
        return chatHistoryDetailMapper.selectList(
                new QueryWrapper<ChatHistoryDetailDO>()
                        .lambda()
                        .eq(ChatHistoryDetailDO::getChatId, chatId)
        );
    }

    public List<ChatHistoryDO> findChatByChatIds(List<Long> chatIds) {
        return chatHistoryMapper.selectList(
                new QueryWrapper<ChatHistoryDO>()
                        .lambda()
                        .in(ChatHistoryDO::getId, chatIds)
        );
    }

    public ChatHistoryDO findChatByChatId(Long chatId) {
        return chatHistoryMapper.selectOne(
                new QueryWrapper<ChatHistoryDO>()
                        .lambda()
                        .eq(ChatHistoryDO::getId, chatId)
        );
    }

    public void appendChatDetailWithUser(String message, Long chatId) {
        int nexOrder = Optional.ofNullable(chatHistoryDetailMapper.getMaxOrder(chatId)).orElse(1) + 1;

        ChatHistoryDetailDO chatHistoryDetailDO = new ChatHistoryDetailDO();
        chatHistoryDetailDO.setChatId(chatId);
        chatHistoryDetailDO.setChatOrder(nexOrder);
        chatHistoryDetailDO.setSendMessage(JSONUtil.toJsonStr(new UserMessageBO(message)));
        chatHistoryDetailDO.setChatRole(ChatRole.USER.getRole());
        chatHistoryDetailDO.setGmtCreate(LocalDateTime.now());
        chatHistoryDetailMapper.insert(chatHistoryDetailDO);

    }

    public void appendChatDetailWithAssistant(String message, Long chatId) {
        int nexOrder = Optional.ofNullable(chatHistoryDetailMapper.getMaxOrder(chatId)).orElse(1) + 1;
        ChatHistoryDetailDO chatHistoryDetailDO = new ChatHistoryDetailDO();
        chatHistoryDetailDO.setChatId(chatId);
        chatHistoryDetailDO.setChatOrder(nexOrder);
        AssistantMessageBO assistantMessageBO = new AssistantMessageBO();
        assistantMessageBO.setMdMessage(message);
//        assistantMessageBO.setMessage("用时" + useTime / 1000 + "秒");
        chatHistoryDetailDO.setSendMessage(JSONUtil.toJsonStr(assistantMessageBO));
        chatHistoryDetailDO.setChatRole(ChatRole.ASSISTANT.getRole());
        chatHistoryDetailDO.setGmtCreate(LocalDateTime.now());
        chatHistoryDetailMapper.insert(chatHistoryDetailDO);

    }


}
